<template>

	<!--顶部新增、查询-->
    <div style="margin-bottom: 10px;">
        <el-button type="primary" style="margin-right: 10px;" @click= "AddMembershipClick">新增会员</el-button>
        <el-input v-model="MembershipSearchInput" style="width: 240px" placeholder="按会员编号搜索" :prefix-icon="Search"/>
    </div>

	<!--会员数据展示表格-->
	<el-table :data="MemberDataTable" style="width: 100%" highlight-current-row>
		<el-table-column fixed prop="membershipID" label="会员ID" align="center"/>
		<el-table-column prop="membershipName" label="会员姓名" align="center"/>
		<el-table-column prop="membershipAge" label="年龄" align="center"/>
		<el-table-column prop="membershipBirthday" label="生日" align="center"/>
		<el-table-column prop="membershipScore" label="积分" align="center"/>
		<el-table-column prop="membershipPhone" label="手机号" align="center"/>
		<el-table-column fixed="right" label="操作" min-width="120" align="center">
		<template #default="ThisRowData">
			<el-button size="small" @click="EditMembershipClick(ThisRowData.row)">修改</el-button>
			<el-button size="small" type="danger" @click="DeleteMembershipClick(ThisRowData.row)">删除</el-button>
		</template>
		</el-table-column>

		<template #empty>
		<el-empty description="暂无会员数据" />
		</template>
	</el-table>

	<!-- 删除对话框 -->
	<el-dialog v-model="DeleteMembershipDialog" title="会员删除提示" width="500">
		<span>是否确定删除该会员？</span><br>
		<span>会员ID: {{ RowMembershipData.membershipID }}</span><br>
		<span>会员姓名: {{ RowMembershipData.membershipName }}</span>
		<template #footer>
		<div class="dialog-footer">
			<el-button @click="DeleteMembershipDialog = false">取消</el-button>
			<el-button type="primary" @click="DeleteMembership">确定</el-button>
		</div>
		</template>
	</el-dialog>

	<!-- 修改对话框 -->
	<el-dialog v-model="EditMembershipDialog" title="会员信息修改" width="500">
		<el-form :model="PutMembershipData">
		<el-form-item label="会员ID">
			<el-input v-model="PutMembershipData.membershipID" disabled />
		</el-form-item>
		<el-form-item label="会员姓名">
			<el-input v-model="PutMembershipData.membershipName" />
		</el-form-item>
		<el-form-item label="年龄">
			<el-input-number v-model="PutMembershipData.membershipAge" :min="0" :max="150" />
		</el-form-item>
		<el-form-item label="生日">
			<el-date-picker
			v-model="PutMembershipData.membershipBirthday"
			type="date"
			placeholder="选择生日"
			format="YYYY-MM-DD"
			value-format="YYYY-MM-DD"
			/>
		</el-form-item>
		<el-form-item label="积分">
			<el-input-number v-model="PutMembershipData.membershipScore" :min="0" :step="1" />
		</el-form-item>
		<el-form-item label="手机号">
			<el-input
			v-model="PutMembershipData.membershipPhone"
			placeholder="请输入11位手机号"
			pattern="^1[3-9]\d{9}$" 
			auto-complete="off"
			/>
		</el-form-item>
		</el-form>
		<template #footer>
		<div class="dialog-footer">
			<el-button @click="EditMembershipDialog = false">取消</el-button>
			<el-button type="primary" @click="PutMembership">确定</el-button>
		</div>
		</template>
	</el-dialog>

	<!-- 新增对话框 -->
	<el-dialog v-model="AddMembershipDialog" title="添加会员" width="500">
		<el-form :model="PostMembershipData">
		<el-form-item label="会员姓名">
			<el-input v-model="PostMembershipData.membershipName" />
		</el-form-item>
		<el-form-item label="年龄">
			<el-input-number v-model="PostMembershipData.membershipAge" :min="0" :max="150" />
		</el-form-item>
		<el-form-item label="生日">
			<el-date-picker
			v-model="PostMembershipData.membershipBirthday"
			type="date"
			placeholder="选择生日"
			format="YYYY-MM-DD"
			value-format="YYYY-MM-DD"
			/>
		</el-form-item>
		<el-form-item label="积分">
			<el-input-number v-model="PostMembershipData.membershipScore" :min="0" :step="1" />
		</el-form-item>
		<el-form-item label="手机号">
			<el-input
			v-model="PostMembershipData.membershipPhone"
			placeholder="请输入11位手机号"
			pattern="^1[3-9]\d{9}$" 
			auto-complete="off"
			/>
		</el-form-item>
		</el-form>
		<template #footer>
		<div class="dialog-footer">
			<el-button @click="AddMembershipDialog = false">取消</el-button>
			<el-button type="primary" @click="PostMembership">确定</el-button>
		</div>
		</template>
	</el-dialog>
</template>

<script lang='ts' setup name='Membership'>

// 导入必要组件
import axios from 'axios';
import { reactive, ref, onMounted, watch } from 'vue';
import { ElNotification } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// 对话框显示参数
const DeleteMembershipDialog = ref(false);
const EditMembershipDialog = ref(false);
const AddMembershipDialog = ref(false);

// 新增：存储全量会员数据
const allMembershipData = ref([]);

// 生命周期钩子
onMounted(async () => {
	await GetMembership();
});

// 表格单行会员数据
let RowMembershipData = reactive({
	membershipID: 0,
	membershipName: '',
	membershipAge: 0,
	membershipBirthday: '',
	membershipScore: 0,
	membershipPhone: ''
});

// 表单验证
function validateForm(formData: any) {
	if (!formData.membershipName?.trim()) {
		ElNotification({
			title: '错误',
			message: '会员姓名必填',
			type: 'error'
		});
		return false;
	}
	
	if (!formData.membershipPhone?.trim()) {
		ElNotification({
			title: '错误',
			message: '手机号必填',
			type: 'error'
		});
		return false;
	}
	
	if (!/^1[1-9]\d{9}$/.test(formData.membershipPhone)) {
		ElNotification({
			title: '错误',
			message: '手机号格式错误（11位数字，以11-19开头）',
			type: 'error'
		});
		return false;
	}
	
	if (formData.membershipAge !== undefined && formData.membershipAge !== null && 
		(formData.membershipAge < 0 || formData.membershipAge > 150)) {
		ElNotification({
			title: '错误',
			message: '年龄需在0-150之间',
			type: 'error'
		});
		return false;
	}
	
	if (!formData.membershipBirthday) {
		ElNotification({
			title: '错误',
			message: '请选择生日',
			type: 'error'
		});
		return false;
	}
	
	return true;
}

// 添加会员回调
function AddMembershipClick() {
	// 重置表单数据
	Object.assign(PostMembershipData, {
		membershipID: 0, 
		membershipName: '',
		membershipAge: 0,
		membershipBirthday: '',
		membershipScore: 0,
		membershipPhone: ''
	});

	// 打开对话框
	AddMembershipDialog.value = true;
}

// 修改会员回调
async function EditMembershipClick(row: any) {
	try {
		const response = await axios.get(`/api/membership/${row.membershipID}`);
		console.log('会员详情:', response.data.data);
		Object.assign(PutMembershipData, response.data.data);
		EditMembershipDialog.value = true;
	} catch (error) {
		ElNotification({
			title: '错误',
			message: '获取会员信息失败',
			type: 'error'
		});
	}
}

// 删除会员回调
function DeleteMembershipClick(row: any) {

	// 存储当前行
	RowMembershipData = row

	// 打开对话框
	DeleteMembershipDialog.value = true;
}

// GET ------------------------------------------ GET //

// GET: 获取的会员数据（过滤后）
const MemberDataTable = ref([]);

// GET: 获取会员数据（存储全量数据）
async function GetMembership() {
	try {
		const response = await axios.get("/api/membership");
		allMembershipData.value = response.data.data || []; // 存储全量数据
		applySearchFilter(); // 应用搜索过滤
		console.log('会员列表:', allMembershipData.value);
	} catch (error) {
		ElNotification({
            title: '错误',
            message: '获取会员列表失败',
            type: 'error'
		});
	}
}

// 新增：前端搜索过滤函数
function applySearchFilter() {
    const searchValue = MembershipSearchInput.value.trim();
    if (!searchValue) {
        // 无搜索词时显示全部数据
        MemberDataTable.value = [...allMembershipData.value];
    } else {
        // 按会员编号模糊过滤（字符串匹配）
        MemberDataTable.value = allMembershipData.value.filter(item => 
            String(item.membershipID).includes(searchValue)
        );
    }
}

// 输入框接收到的会员编号
let MembershipSearchInput = ref('');

// 修改：监听输入并应用过滤（移除原有API请求）
watch(
	MembershipSearchInput, 
	(_newVal, _oldVal) => {
		applySearchFilter();
	}
);

// 移除原有搜索请求函数
// async function GetMembershipById(){...}

// POST ------------------------------------------ POST //

// POST: 添加的会员数据
const PostMembershipData = reactive({
	membershipID: 0, 
	membershipName: '',
	membershipAge: 0,
	membershipBirthday: '',
	membershipScore: 0,
	membershipPhone: ''
});

async function PostMembership() {

	// 表单检查
	if (!validateForm(PostMembershipData)){return}

	// 发送请求
	try {
		await axios.post("/api/membership", {
			membershipName: PostMembershipData.membershipName,
			membershipAge: PostMembershipData.membershipAge,
			membershipBirthday: PostMembershipData.membershipBirthday,
			membershipScore: PostMembershipData.membershipScore,
			membershipPhone: PostMembershipData.membershipPhone
		});
		
		ElNotification({
			title: '成功',
			message: '新增会员成功',
			type: 'success'
		});
		await GetMembership(); // 刷新数据并重新过滤
	} catch (error) {
		ElNotification({
			title: '错误',
			message: '新增会员失败',
			type: 'error'
		});
	}
	AddMembershipDialog.value = false;
}

// PUT ------------------------------------------ PUT //

// PUT: 修改的会员数据
const PutMembershipData = reactive({
	membershipID: 0,
	membershipName: '',
	membershipAge: 0,
	membershipBirthday: '',
	membershipScore: 0,
	membershipPhone: ''
});

// PUT: 修改会员数据
async function PutMembership() {

	// 表单检查
	if (!validateForm(PutMembershipData)){return}

	// 发送请求
	try {
		// 发送更新请求（使用 membershipID 作为路径参数）
		await axios.put(`/api/membership/${PutMembershipData.membershipID}`, {
			membershipName: PutMembershipData.membershipName,
			membershipAge: PutMembershipData.membershipAge,
			membershipBirthday: PutMembershipData.membershipBirthday,
			membershipScore: PutMembershipData.membershipScore,
			membershipPhone: PutMembershipData.membershipPhone
		});
		ElNotification({
			title: '成功',
			message: '修改会员信息成功',
			type: 'success'
		});
		await GetMembership(); // 刷新数据并重新过滤
	} catch (error) {
		ElNotification({
			title: '错误',
			message: '修改会员失败',
			type: 'error'
		});
	}
	EditMembershipDialog.value = false;
}

// DELETE ------------------------------------------ DELETE //

// DELETE: 删除会员数据
async function DeleteMembership() {
	try {
		await axios.delete(`/api/membership/${RowMembershipData.membershipID}`);
		ElNotification({
		title: '成功',
		message: '删除会员成功',
		type: 'success'
		});
		await GetMembership(); // 刷新数据并重新过滤
	} catch (error) {
		ElNotification({
		title: '错误',
		message: '删除会员失败',
		type: 'error'
		});
	}
	DeleteMembershipDialog.value = false;
}


</script>

<style scoped>

/* 表格居中设置 */
.el-table-column {
    text-align: center;
}

</style>